/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package abricots.game.state;

import abricots.MyLog;
import abricots.entity.BasicEntity;
import abricots.net.common.GameMessage.CommandsMessage;
import abricots.net.common.GameMessage.WorldDiffMessage;
import abricots.net.common.MessageDispatcher;
import abricots.entity.Entity;
import abricots.game.EntityFactory;
import abricots.game.GameEnv;
import abricots.net.common.GameMessage;
import abricots.net.common.GameMessage.GameTimeSyncMessage;
import abricots.net.common.GameMessage.EntityMessage;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.minlog.Log;

/**
 *
 * @author charly
 */
public class TestStateMessageDispatcher extends MessageDispatcher {
   private final MyLog log = new MyLog(getClass().getSimpleName(), Log.LEVEL_TRACE);
   private TestState gameState;
   private GameEnv env;

   public TestStateMessageDispatcher(TestState state, GameEnv env) {
      this.gameState = state;
      this.env = env;
   }

   @Override
   public void dispatchGameSyncMessage(GameTimeSyncMessage message, Connection connection) {
      long tripTime = connection.getReturnTripTime();
      long oldGameTime = env.getTimeManager().getGameTime();
      long newGameTime = message.gameTime - tripTime;
      long newNewGameTime = oldGameTime + (newGameTime - oldGameTime) / 3;
      env.getTimeManager().setGameStartTime(System.currentTimeMillis() - newNewGameTime);
   }

   @Override
   public void dispatchEntitymessage(EntityMessage message, Connection connection) {
      GameMessage.EntityMessage entityMessage = (GameMessage.EntityMessage) message;
      log.trace("Receved new Entity message " + entityMessage.toString());
      if (entityMessage.entityId >= 0) {
         if (entityMessage.localEntityId >= 0) {
            // this is ours
            env.getEntitiesManager().validateEntity(entityMessage.localEntityId, entityMessage.entityId);
            BasicEntity entity = (BasicEntity) env.getEntitiesManager().getEntity(entityMessage.entityId);
            entity.onValidation();
            log.debug("Validated entity " + entityMessage.toString());
         } else {
            if (!env.getEntitiesManager().containsEntity(entityMessage.entityId)) {
               Entity newEntity = EntityFactory.build(entityMessage.entityTypeId);
               newEntity.register(env);
               env.getEntitiesManager().validateEntity(newEntity.getId(), entityMessage.entityId);
               log.debug("New entity added: " + entityMessage.toString());
            }
         }
      }
   }

   @Override
   public void dispatchWorldDiffMessage(WorldDiffMessage message, Connection connection) {
      gameState.addDiffMessage(message);
   }

   @Override
   public void dispatchCommandsMessage(CommandsMessage message, Connection connection) {
   }
}
